package com.demo03.test01;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockTest {
    public static void main(String[] args) {
        Outer outer = new Outer();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    outer.output("123456789123456789");
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    outer.output("asdfghjklqwertyuizvb");
                }
            }
        }).start();
    }

    static class Outer {
        Lock lock = new ReentrantLock();

        public void output(String str) {
            int len = str.length();
            try {
                lock.lock();
                for (int i = 0; i < len; i++) {
                    System.out.print(str.charAt(i));
                }
                System.out.println();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        }
    }
}
